package my.study.com.mysql.jdbc.examples.example1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Ex2 {

	/**
	 * Retrieving AUTO_INCREMENT column values using SELECT LAST_INSERT_ID()
	 * 
	 * @param args
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static void main(String[] args) throws SQLException,
			InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "fanhongjie";

		Class.forName("com.mysql.jdbc.Driver").newInstance();
		Connection conn = DriverManager.getConnection(url, user, password);
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();

			stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
			stmt.executeUpdate("CREATE TABLE autoIncTutorial ("
					+ "priKey INT NOT NULL AUTO_INCREMENT, "
					+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
			stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) "
					+ "values ('Can I Get the Auto Increment Field?')");
			//
			// Use the MySQL LAST_INSERT_ID()
			// function to do the same thing as getGeneratedKeys()
			//
			int autoIncKeyFromFunc = -1;
			rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
			if (rs.next()) {
				autoIncKeyFromFunc = rs.getInt(1);
			} else {
				// throw an exception from here
			}
			rs.close();
			System.out.println("Key returned from "
					+ "'SELECT LAST_INSERT_ID()': " + autoIncKeyFromFunc);
		} finally {
			if (rs != null) {
				rs.close();

			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
	}
}
